<template>
  <div class="bind-box-item">
    <!-- prizeCategory  0是实物，1是虚拟 -->
    <div class="box-status-time">
      <span class="time">{{ info.createTime }}</span>
      <span class="status">{{ StatusDescEums[info.status] }}</span>
    </div>
    <commodity-item :boxInfo="info"></commodity-item>
    <div
      class="prize-info address-box"
      v-if="StatusEums.PRIZE_DELIVERED === info.status&&info.prizeCategory===1"
    >
      <van-button
        plain
        hairline
        type="primary"
        round
        @click="checkStatus"
      >查询状态</van-button>
      <van-button
        plain
        hairline
        type="primary"
        round
        @click="onConfirmDeliveryGoods"
      >确认收货</van-button>
    </div>
    <div
      class="prize-info address-box"
      v-if="StatusEums.OPENED === info.status"
    >
      <van-button
        plain
        hairline
        type="primary"
        round
        @click="convertCash"
      >折换现金券</van-button>
      <van-button
        plain
        hairline
        type="primary"
        round
        @click="enterToFillAddress"
        v-if="info.prizeCategory === 0"
      >填写地址</van-button>
      <van-button
        plain
        hairline
        type="primary"
        round
        @click="enterToFillAddress"
        v-if="info.prizeCategory === 1"
      >填写手机号</van-button>
    </div>
    <div
      class="prize-info"
      v-if="StatusEums.POSITIVE === info.status"
    >
      <span></span>
      <van-button
        plain
        hairline
        type="primary"
        round
        @click="openBox"
      >开盲盒</van-button>
    </div>
    <div
      class="expressage-info"
      v-if="StatusEums.PRIZE_DELIVERED === info.status && info.expressCode"
    >
      <div>
        <span class="order-info">快递单号：{{ info.expressCode }}</span>
        <van-button
          plain
          hairline
          type="primary"
          round
          class="tag-read"
          @click="copyText(info.expressCode, $event)"
        >复制</van-button>
      </div>
      <van-button
        plain
        hairline
        type="primary"
        round
        @click="onConfirmDeliveryGoods"
      >确认收货</van-button>
    </div>
    <div
      class="prize-info"
      v-if="info.couponExpirationTime && StatusEums.POSITIVE !== info.status"
    >
      <span>过期时间：{{ info.couponExpirationTime }}</span>
      <van-button
        plain
        hairline
        type="primary"
        round
        @click="onExchangeClick"
        :disabled="isPast || !info.couponBalance"
      >立即兑换</van-button>
    </div>
    <div
      class="prize-info"
      v-if="StatusEums.POSITIVE !== info.status && info.couponStatus === 1"
    >
      <span></span>
      <van-button
        plain
        hairline
        type="primary"
        round
        @click="activateCashCoupun"
        :disabled="isPast || !info.couponBalance"
      >立即激活</van-button>
    </div>
    <exchange-action-sheet
      ref="actionSheet"
      title="选择兑换账户"
      cancelText="取消"
      :exchangeInfo="info"
      @selectUser="selectUser"
    >
    </exchange-action-sheet>
    <bind-box-item-prize
      @acceptBlindbox="acceptBlindbox"
      :poster="info.prizePoster"
      :prizeInfo="prizeInfo"
      step="second"
      ref="overlay"
    ></bind-box-item-prize>
    <dialog-custom
      ref="dialog"
      title="现金券已入袋，请尽快使用"
      confirmButtonText="我知道了"
      confirmButtonColor="#1677FF"
      @confirm="closeDialog"
      @cancel="closeDialog"
    ></dialog-custom>
  </div>
</template>

<script>
const StatusDescEums = {
  1: "待开启", //未打开
  2: "待领取", //已打开
  3: "待发货", //已填写收货信息
  4: "已发货",
  5: "已收货",
};
const StatusEums = {
  POSITIVE: 1,
  OPENED: 2,
  EXPRESS_INFO_SUBMITTED: 3,
  PRIZE_DELIVERED: 4,
  PRIZE_RECEIVED: 5,
};
import { mapGetters } from "vuex";
import Clipboard from "clipboard";
import { Button } from "vant";
import CommodityItem from "./CommodityItem";
import ExchangeActionSheet from "./ExchangeActionSheet";
import BindBoxItemPrize from "./BindBoxItemPrize";
import DialogCustom from "./DialogCustom";
import apiCash from "@/common/api/apiCash";
import apBox from "@/common/api/apBox";
import Exchange from "@/views/mixin/exchange";

import { Dialog } from "vant";

export default {
  name: "BindBoxItem",
  components: {
    [CommodityItem.name]: CommodityItem,
    [ExchangeActionSheet.name]: ExchangeActionSheet,
    [BindBoxItemPrize.name]: BindBoxItemPrize,
    [DialogCustom.name]: DialogCustom,
    [Button.name]: Button,
  },
  mixins: [Exchange],
  props: {
    bindBoxInfo: {
      type: Object,
      default: {},
    },
  },
  watch: {
    bindBoxInfo: {
      deep: true,
      handler: function (newVal) {
        this.info = newVal;
        this.currCashInfo = newVal;
        if (this.currCashInfo.couponBalance) {
          this.$set(
            this.currCashInfo,
            "balance",
            this.currCashInfo.couponBalance / 100
          );
        }
      },
    },
  },
  computed: {
    ...mapGetters(["userInfo"]),
    isPast: function () {
      if (this.info.couponExpirationTime) {
        let infoTime = this.info.couponExpirationTime.replace(/-/g, "/");
        if (new Date(infoTime) > new Date()) {
          return false;
        }
        return true;
      }
      return false;
    },
  },
  data() {
    return {
      StatusDescEums: StatusDescEums,
      StatusEums: StatusEums,
      info: {},
      currCashInfo: {}, //兑换信息
      prizeInfo: {}, //产品信息
      cashInfo: {},
    };
  },
  created() {
    this.info = this.bindBoxInfo;
    this.currCashInfo = this.bindBoxInfo;
    if (this.currCashInfo.couponBalance) {
      this.$set(
        this.currCashInfo,
        "balance",
        this.currCashInfo.couponBalance / 100
      );
    }
  },
  methods: {
    //  查询状态
    checkStatus() {
      this.$router.push({
        path: "/rechargeStatus",
        query: {
          boxInfo: JSON.stringify(this.info),
          boxId: this.info.id,
        },
      });
    },
    // 点击折换现金券
    convertCash() {
      this.$toast.loading();
      apiCash
        .getExchangeableCashCoupon({
          userBoxId: this.info.id,
          userId: this.userInfo.userId,
        })
        .then((data) => {
          this.cashInfo = data.data;
          this.showDialog();
          this.$toast.clear();
        });
    },
    showDialog() {
      Dialog.confirm({
        title: "提示",
        message: "该奖品可以折换" + this.cashInfo.name,
        confirmButtonText: "折换",
      })
        .then(() => {
          this.exchangeUserBoxPrize();
        })
        .catch(() => {});
    },
    //  折换
    exchangeUserBoxPrize() {
      apiCash
        .exchangeUserBoxPrize({
          userBoxId: this.info.id,
          userId: this.userInfo.userId,
        })
        .then(() => {
          this.$toast.clear();
          this.$toast.success("折换成功，请前往折换已查看");
          setTimeout(() => {
            this.$emit("exchangeUserBoxPrizeSuccess");
          }, 1000);
        });
    },
    //  进入填写地址
    enterToFillAddress() {
      this.$router.push({
        path: "/fillAddress",
        query: {
          prizeInfo: JSON.stringify(this.info),
          boxId: this.info.id,
        },
      });
    },
    //  关闭弹框
    closeDialog() {
      this.$emit("openBoxSuccess");
    },
    // 收下盲盒
    acceptBlindbox() {
      this.$refs.overlay.hideOverlay();
      if (this.prizeInfo.type === 0) {
        this.$refs.dialog.showDialog();
        return;
      }
      this.$router.push({
        path: "/fillAddress",
        query: {
          prizeInfo: JSON.stringify(this.prizeInfo),
          boxId: this.info.id,
        },
      });
    },
    // 开盲盒
    openBox() {
      this.$toast.loading();
      apBox
        .openBox({
          id: this.info.id,
        })
        .then((data) => {
          this.openBoxSuccess(data.data);
          this.$toast.clear();
        });
    },
    // 打开盲盒成功
    openBoxSuccess(data) {
      this.$refs.overlay.showOverlay();
      this.prizeInfo = data;
      this.$set(this.prizeInfo, "id", this.info.id);
    },
    // 点击立即兑换
    onExchangeClick() {
      this.$refs.actionSheet.showSheet();
    },
    //  立即激活
    activateCashCoupun() {
      this.$emit("activateCashCoupun", this.info);
    },
    // 复制订单号
    copyText(text, e) {
      const clipboard = new Clipboard(e.target, {
        text: () => text,
      });
      clipboard.on("success", () => {
        this.copySuccess();
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on("error", () => {
        // 不支持复制
        this.copyFail();
        // 释放内存
        clipboard.destroy();
      });
      // 解决第一次点击不生效的问题，如果没有，第一次点击会不生效
      clipboard.onClick(e);
    },
    copySuccess() {
      this.$toast.success("复制成功");
    },
    copyFail() {
      this.$toast.warning("该浏览器不支持自动复制");
    },
    //  确认收货
    onConfirmDeliveryGoods() {
      this.$emit("confirmDeliveryGoods", this.info);
    },
  },
};
</script>

<style scoped lang="less">
.bind-box-item {
  width: 100%;
  box-sizing: border-box;
  padding: 24px;
  background: #ffffff;
  border-radius: 20px;

  .box-status-time {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 24px;
    border-bottom: 1px solid #f0f0f0;

    .time {
      font-size: 24px;
      color: #888888;
    }

    .status {
      font-size: 26px;
      color: #df5438;
    }
  }

  .expressage-info,
  .prize-info {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    align-items: center;

    span {
      font-size: 20px;
      color: #888888;
    }
  }
  .prize-info.address-box {
    justify-content: flex-end;
    .van-button:first-child {
      margin-right: 30px;
    }
  }
  .expressage-info {
    justify-content: space-between;
    > div {
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: center;
      .van-button--plain.van-button--primary {
        .van-button__text {
          font-size: 20px;
          color: #3b6bd8;
        }
      }
    }
  }

  .prize-info,
  .expressage-info {
    > .van-button--plain.van-button--primary {
      height: 66px;
      background: #ffffff;
      border: 1px solid #3f87f0;
      padding: 0 29px;
      background: none;
      span {
        font-size: 26px;
        color: #3b6bd8;
      }
    }
  }

  .van-card {
    padding-left: 0;
    padding-right: 0;
  }
  .van-button::before,
  .van-button--hairline::after {
    display: none;
  }
}
.cash-info-box {
  img {
    box-sizing: border-box;
    width: 100%;
    padding: 25px 20px 0;
  }
}
</style>
